﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace HenhouseEnvironmentCtrl
{
    public partial class ManageCDKForm : Form
    {
        public ManageCDKForm()
        {
            InitializeComponent();
        }

        private void ManageCDKForm_Load(object sender, EventArgs e)
        {
            LoadCDKData();
            dgvCDKData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvCDKData.MultiSelect = false;
            dgvCDKData.ContextMenuStrip = contextMenuStrip1;
        }

        private void LoadCDKData()
        {
            using (SqlConnection conn = DBConnection.CreateConnection())
            {
                DBConnection.Open(conn);
                SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM CDK", conn);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                dgvCDKData.DataSource = dt;
                DBConnection.Close(conn);
            }
        }

        private void BtnSearch_Click(object sender, EventArgs e)
        {
            string query = "SELECT * FROM CDK WHERE 1=1";

            // CDK 字段搜索
            if (!string.IsNullOrEmpty(txtCDK.Text))
            {
                query += $" AND CDK LIKE '%{txtCDK.Text}%'";
            }

            // 可用次数搜索，只显示等于指定值的记录
            if (!string.IsNullOrEmpty(txtAvailableUses.Text) && int.TryParse(txtAvailableUses.Text, out int uses))
            {
                query += $" AND AvailableUses = {uses}";
            }

            // 可用性过滤
            if (chkIsAvailable.Checked)
            {
                query += $" AND IsAvailable = 1";
            }

            // 执行查询并更新 DataGridView
            using (SqlConnection conn = DBConnection.CreateConnection())
            {
                DBConnection.Open(conn);
                SqlDataAdapter sda = new SqlDataAdapter(query, conn);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                dgvCDKData.DataSource = dt;
                DBConnection.Close(conn);
            }
        }


        private void BtnAddCDK_Click(object sender, EventArgs e)
        {
            AddCDKForm addCDKForm = new AddCDKForm();
            if (addCDKForm.ShowDialog() == DialogResult.OK)
            {
                LoadCDKData();
            }
        }

        private void BtnBatchAddCDK_Click(object sender, EventArgs e)
        {
            try
            {
                using (InputDialog batchDialog = new InputDialog("请输入要生成的CDK条数:", "批量添加CDK"))
                {
                    if (batchDialog.ShowDialog() == DialogResult.OK)
                    {
                        if (int.TryParse(batchDialog.InputValue, out int batchCount) && batchCount > 0)
                        {
                            using (InputDialog usesDialog = new InputDialog("请输入每个CDK的可用次数:", "批量添加CDK"))
                            {
                                if (usesDialog.ShowDialog() == DialogResult.OK)
                                {
                                    if (int.TryParse(usesDialog.InputValue, out int availableUses) && availableUses > 0)
                                    {
                                        using (SqlConnection conn = DBConnection.CreateConnection())
                                        {
                                            DBConnection.Open(conn);

                                            for (int i = 0; i < batchCount; i++)
                                            {
                                                string cdk = Guid.NewGuid().ToString().Substring(0, 8);

                                                SqlCommand checkCmd = new SqlCommand("SELECT COUNT(*) FROM CDK WHERE CDK = @cdk", conn);
                                                checkCmd.Parameters.AddWithValue("@cdk", cdk);
                                                int count = (int)checkCmd.ExecuteScalar();

                                                if (count == 0)
                                                {
                                                    SqlCommand cmd = new SqlCommand("INSERT INTO CDK (CDK, IsAvailable, AvailableUses) VALUES (@cdk, @isAvailable, @availableUses)", conn);
                                                    cmd.Parameters.AddWithValue("@cdk", cdk);
                                                    cmd.Parameters.AddWithValue("@isAvailable", true);
                                                    cmd.Parameters.AddWithValue("@availableUses", availableUses);
                                                    cmd.ExecuteNonQuery();
                                                }
                                            }

                                            DBConnection.Close(conn);
                                            LoadCDKData();
                                        }

                                        MessageBox.Show($"成功批量添加 {batchCount} 个CDK，每个CDK可用次数为 {availableUses} 次！");
                                    }
                                    else
                                    {
                                        MessageBox.Show("请输入有效的可用次数。");
                                    }
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("请输入有效的CDK条数。");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"批量添加CDK失败：{ex.Message}");
            }
        }

        private void BtnEditCDK_Click(object sender, EventArgs e)
        {
            if (dgvCDKData.SelectedRows.Count > 0)
            {
                int selectedRowIndex = dgvCDKData.SelectedRows[0].Index;
                int cdkId = Convert.ToInt32(dgvCDKData.Rows[selectedRowIndex].Cells["CDKId"].Value);

                EditCDKForm editCDKForm = new EditCDKForm(cdkId);
                if (editCDKForm.ShowDialog() == DialogResult.OK)
                {
                    LoadCDKData();
                }
            }
            else
            {
                MessageBox.Show("请选择要编辑的CDK。");
            }
        }

        private void BtnDeleteCDK_Click(object sender, EventArgs e)
        {
            if (dgvCDKData.SelectedRows.Count > 0)
            {
                int selectedRowIndex = dgvCDKData.SelectedRows[0].Index;
                int cdkId = Convert.ToInt32(dgvCDKData.Rows[selectedRowIndex].Cells["CDKId"].Value);

                DialogResult dialogResult = MessageBox.Show($"确定要删除ID为{cdkId}的CDK吗？", "提示", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.No)
                    return;

                using (SqlConnection conn = DBConnection.CreateConnection())
                {
                    DBConnection.Open(conn);
                    SqlCommand cmd = new SqlCommand($"DELETE FROM CDK WHERE CDKId = {cdkId}", conn);
                    cmd.ExecuteNonQuery();
                    DBConnection.Close(conn);
                }

                LoadCDKData();
            }
            else
            {
                MessageBox.Show("请选择要删除的CDK。");
            }
        }

        private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            BtnDeleteCDK_Click(sender, e);
        }

        private void BtnBatchDeleteCDK_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("您确定要删除所有选中的CDK吗？", "提示", MessageBoxButtons.OKCancel);
            if (dialogResult == DialogResult.Cancel)
                return;

            try
            {
                using (SqlConnection conn = DBConnection.CreateConnection())
                {
                    DBConnection.Open(conn);
                    foreach (DataGridViewRow row in dgvCDKData.Rows)
                    {
                        if (Convert.ToBoolean(row.Cells["chkSelect"].Value))
                        {
                            int cdkId = Convert.ToInt32(row.Cells["CDKId"].Value);
                            SqlCommand cmd = new SqlCommand($"DELETE FROM CDK WHERE CDKId = {cdkId}", conn);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    DBConnection.Close(conn);
                }
                MessageBox.Show("已删除选中的所有CDK");
                LoadCDKData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除选中CDK失败：{ex.Message}");
            }
        }
        private void ChkSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dgvCDKData.Rows)
            {
                DataGridViewCheckBoxCell chkBox = (DataGridViewCheckBoxCell)row.Cells["chkSelect"];
                chkBox.Value = chkSelectAll.Checked;
            }
        }

        private void BtnBack_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
